#include "UdpServer.hpp"
#include "Comm.hpp"
#include <memory>
#include <cstdio>
#include <vector>
#include <string>
using namespace std;
vector<string> black_words = {"rm", "unlink",
                              "cp",
                              "man"};
bool SafeCheck(std::string command)
{

    for (auto tmp : black_words)
    {
        if (command == tmp)
        {
            return false;
        }
    }
    return true;
}
std::string OnMessageDefault(std::string request)
{
    return request + "[haha, got you!!]";
}
string ExecuteCommand(std::string command)
{
    if (!SafeCheck(command))
    {
        return "bad man";
    }
    cout << "get message" << command << endl;
    FILE *fp = popen(command.c_str(), "r");
    if (fp == nullptr)
    {
        cout << "打开文件成功" << endl;
        return "excute error reson unknow";
    }
    string response;
    char buffer[1024];
    while (true)
    {
        char *s = fgets(buffer, sizeof(buffer), fp);
        if(!s) break;
        else
        response += buffer;
    }
    pclose(fp);
    cout << response << endl;
    return response.empty() ? "sucess" : response;
}
void Usage(std::string proc)
{
    // std::cout<<"Usage:\n\t"<<proc<<"local_ip local_port\n"<<endl;
    std::cout << "Usage:\n\t" << proc << "local_port\n"
              << endl;
}
int main(int arge, char *argv[])
{
    string use = argv[0];
    if (arge != 2)
    {
        Usage(use);
        return Usage_Err;
    }
    // std::string ip=argv[1];
    uint16_t port = std::atoi(argv[1]);
    std::unique_ptr<Udpserver> usvr = std::make_unique<Udpserver>(ExecuteCommand, port);
    usvr->Init();
    usvr->Start();
    return 0;
}